import {AdvOTImage} from "./AdvOTImage";
import property = cc._decorator.property;
import Wx from "../../../framework/wx/Wx"
import ccclass = cc._decorator.ccclass;

@ccclass()
export default class AdvOTComponent extends cc.Component {

    @property(cc.Sprite)
    private showIcon: cc.Sprite = null;

    public onLoad() {
        this.initLayaIcon();
        if (this.showIcon) {
            this.showIcon.node.on(cc.Node.EventType.TOUCH_END, this.onClick, this)
        } else {
            console.warn("AdvOT 推广组件未设置显示节点.")
        }
    }

    public onDestroy() {
        if (this.showIcon) {
            this.showIcon.node.off(cc.Node.EventType.TOUCH_END, this.onClick, this);
        }
    }

    private onClick() {
        if (AdvOTImage) {
            AdvOTImage.navigateToMiniProgram();
        }
    }

    private initLayaIcon() {
        if (!this.showIcon) {
            return;
        }
        this.showIcon.node.active = false;
        if (cc.sys.platform === cc.sys.IPHONE || cc.sys.os == cc.sys.OS_IOS) {
            console.log("iphone系统,不显示推广", cc.sys.os);
            return;
        }
        if (AdvOTImage) {
            AdvOTImage.start((show) => {
                this.showIcon.node.active = !!show;
            });
            AdvOTImage.change((show, icon) => {
                this.showIcon.node.active = !!show;
                if (show) {
                    Wx.createImage(icon).then(img => {
                        if (img) {
                            this.showIcon.spriteFrame = img;
                            const size = img.getOriginalSize();
                            if (size.width > 100) {
                                this.showIcon.node.width = 100;
                            }
                            if (size.height > 100) {
                                this.showIcon.node.height = 100;
                            }
                        }
                    })
                }
            });
        }
    }
}

